<template>
  <div>
    <el-upload
      action="#"
      :http-request="uploadQiniuCloud"
      ref="upload"
      :file-list="fileData"
      :on-change="beforeUpload"
      :class="{hide:hideUploadEdit}"
      list-type="picture-card"
      :show-file-list="false"
      multiple
      drag
      :limit="limit"
      accept=".jpg,.jpeg,.gif,.png,.bmp,.mp4,.mov,.avi,.mp3,.ogg,.rmvb,.mkv,"
      auto-upload="true"
    >
      <i class="el-icon-upload"></i>
      <div style="position: absolute;top: 44px;width: 100%;">将文件拖到此处，或<em>点击上传</em></div>
    </el-upload>
    <div v-if="fileMap.length > 0" style="margin-top: 3em">
      <ul class="el-upload-list el-upload-list--picture-card">
        <li v-for="(item,index) in fileMap" :key="index" class="el-upload-list__item is-ready">
            <span v-if="item.type === 'image' || item.type === 'video'">
              <el-progress v-if="item.progress !== 100" type="circle" :percentage="item.progress"></el-progress>
              <span v-if="item.url === '-1'">上传失败</span>
              <img v-if="item.type === 'image' && item.progress === 100 && item.url !=='-1' "
                   class="el-upload-list__item-thumbnail creative" :src="item.url" alt="">
              <video v-if="item.type  === 'video' && item.progress === 100 && item.url !=='-1' "
                     class="el-upload-list__item-thumbnail creative" :src="item.url"></video>
             <span class="el-upload-list__item-actions">
                <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(item)"><i
                  class="el-icon-zoom-in"></i></span>
                <span v-if="item.type  === 'video'" class="el-upload-list__item-preview"><i
                  class="el-icon-video-camera"></i></span>
                <span v-if="item.type === 'image'" class="el-upload-list__item-preview"><i
                  class="el-icon-picture-outline"></i></span>
                <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(item,index)"><i
                  class="el-icon-delete"></i></span>
              </span>
            </span>
        </li>
      </ul>
    </div>
    <el-dialog :visible.sync="dialogVisible" :modal-append-to-body="false" top="0px;"
               :close-on-click-modal="false" :before-close="handleClose" :append-to-body="true" width="80%">
      <div style="display: flex;justify-content: center;align-items: center">
        <img v-show="dialogType === 'image'" :style="previewStyle()" :src="dialogImageUrl">
        <video v-show="dialogType === 'video'" :src="dialogImageUrl" ref="video" :style="previewStyle()"
               controls="controls"></video>
      </div>
    </el-dialog>
  </div>
</template>
<script>

  import ObsClient from "esdk-obs-browserjs";
  import * as qiniuTools from "../../util/qinnu_upload";

  var obsClient;
export default {
  name: 'upload_obs',
  props: {
    fileList: {
      type: Array,
    },
    limit: {
      type: String
    }
  },
  data() {
    return {
      dialogType: '',
      dialogImageUrl: '',//dialog内的文件
      dialogVisible: false,
      disabled: false,
      // fileList:[],//素材列表
      fileData: [],
      hideUploadEdit: false,
      fileMap: [],
    }
  },
  watch: {
    fileList: {
      deep: true,
      handler(val, old) {
        if (val === old) {
          return
        }
        this.hideUploadEdit = this.fileList >= this.limit
        this.fileData = this.fileList
        this.fileMap = this.fileList
        this.fileMap.map(item => {
          item['type'] = this.creativeType(item)
          item['progress'] = 100
        })
      }
    },
  },
  mounted() {
    this.initObs();
  },
  methods: {
    initObs() {

    },
    callbackFunc(){
      console.log("callback")
      this.$emit("callbackFunc")
    },
    previewStyle() {
      let height = ((window.innerHeight < 300) ? 300 : (window.innerHeight - 160));
      return {
        maxWidth: '100%',
        maxHeight: height + 'px'
      };
    },
    beforeUpload(file, fileList) {
      if (fileList.length > this.limit) {
        this.postMessage("上传的文件数量一次性不可超过" + this.limit + "个!", "warning");
        this.remove(file)
        return false;
      }
      const extension = ["image","video"].includes(this.creativeType(file));
      if (!extension) {
        this.postMessage("上传的文件格式只能是.jpg,.jpeg,.gif,.png,.bmp,.mp4,.mov,.avi,.mp3,.ogg,.rmvb,.mkv!", "warning");
        this.remove(file);
        return false;
      } else if (file.size > 100 * 1024 * 1024) {
        this.postMessage("上传的单个文件不能超过100M!", "warning");
        this.remove(file)
        return false;
      } else {
        let totalSize = 0;
        fileList.forEach((f) => {
          totalSize += f.size;
        });
        if (totalSize > 500 * 1024 * 1024) {
          this.postMessage("上传的所有文件不能超过500M!", "warning");
          this.remove(file)
          return false;
        }
      }
      this.fileMap.push({
        uid: file.uid,
        name: file.name,
        url: file.url,
        progress: 0,
        type: this.creativeType(file)
      })
      this.hideUploadEdit = fileList.length >= this.limit;
      return true;
    },

    uploadQiniuCloud(file){
      let self = this
      let fileData = qiniuTools.getFileData(file)
      let callback = {
        next(res){
          let fileIdx = self.fileMap.findIndex(item => item.uid === file.file.uid);
          if(fileIdx !== -1) {
            self.fileMap[fileIdx].progress =
              Math.trunc(res.total.percent)
          }
        },
        error(err){
          this.$message({
            type: 'error',
            message: '图片上传失败！' + JSON.stringify(err)
          })
          let fileIdx = self.fileMap.findIndex(item => item.uid === file.file.uid);
          if(fileIdx !== -1) self.fileMap[fileIdx].url =
            '-1'
        },
        complete(res){
          let fileIdx = self.fileMap.findIndex(item => item.uid === file.file.uid);
          if(fileIdx !== -1) {
            self.fileMap[fileIdx].url = 'http://' + fileData.server + '/' + res.key
          }
          self.callbackFunc()
        }
      }
      let uploader = qiniuTools.uploadQiniuCloud(file, fileData)
      uploader.subscribe(callback)
    },


    //上传华为云
    uploadClient(file) {
      let self = this
      let fileType = this.creativeType(file.file);
      let fileData = {
        server: 'obs.cn-east-3.myhuaweicloud.com',
        bucket: fileType === 'image' ? 'ads4each-image-full-size'
          : (fileType != null && fileType !== '') ? 'ads4each-video-full-size' : '',
        name: Math.floor((Math.random() + Math.floor(Math.random() * 9 + 1)) * 10 ** (13 - 1)) + '',
        localName: file.file.name,
      }
      obsClient = new ObsClient({
        access_key_id: 'BVIEDCKS1F8VMR1FIOO8',
        secret_access_key: 'k3IQibnpbaqISScliV435aiwYjrDwaJwAh2p574s',
        server: fileData.server
      });

      //获取上传进度
      let callback = (transferredAmount, totalAmount) => {
        let fileIdx = this.fileMap.findIndex(item => item.uid === file.file.uid);
        if(fileIdx != -1) this.fileMap[fileIdx].progress =
          Math.trunc(transferredAmount * 100.0 / totalAmount)
      };

      obsClient.putObject({
        Bucket: fileData.bucket,//判断是图片还是视频
        Key: fileData.name + "."+fileData.localName.split('.')[fileData.localName.split('.').length - 1].split('?')[0],
        SourceFile: file.file,
        ProgressCallback: callback
      }, (err, result) => {
        if (err) {
          this.$message({
            type: 'error',
            message: '图片上传失败！'
          })
          let fileIdx = self.fileMap.findIndex(item => item.uid === file.file.uid);
          if(fileIdx != -1) self.fileMap[fileIdx].url =
            '-1'
          // this.handleRemove(file)
        } else {
          let self = this
          let fileIdx = self.fileMap.findIndex(item => item.uid === file.file.uid);
          if(fileIdx != -1) self.fileMap[fileIdx].url =
            'https://' + fileData.bucket + '.' + fileData.server + '/' + fileData.name + '.' +
            fileData.localName.split('.')[fileData.localName.split('.').length - 1].split('?')[0]
        }
      });
    },
    uploadCompleted() {
      let uploadingCount = 0;
      this.fileMap.map(file => {
        if(file.progress != 100) {
          uploadingCount ++;
        } else if(file.url.toLowerCase().startsWith('blob:')) {
          uploadingCount ++;
        }
      })
      return (uploadingCount == 0);
    },
    postMessage(msg, type) {
      let self = this;
      if (self.postSingleMessageDisable) {
        return;
      }
      self.postSingleMessageDisable = true;
      self.$message({
        message: msg,
        type: type,
        onClose: () => {
          self.postSingleMessageDisable = false;
        }
      });
    },
    //删除素材
    handleRemove(v,i) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let fileList = this.$refs.upload.uploadFiles;
        fileList.splice(i, 1);
        this.fileData = fileList
        this.hideUploadEdit = fileList.length >= this.limit
        this.fileMap.forEach((item,index) => {
          if (item.url === v.url) {
            this.fileMap.splice(index, 1)
          }
        })
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    remove(v,i){
      let fileList = this.$refs.upload.uploadFiles;
      fileList.splice(i, 1);
      this.fileData = fileList
      this.hideUploadEdit = fileList.length >= this.limit
      this.fileMap.forEach((item,index) => {
        if (item.url === v.url) {
          this.fileMap.splice(index, 1)
        }
      })
    },
    //素材放大
    handlePictureCardPreview(v) {
      if (v.type === 'image') {
        this.dialogType = 'image'
      } else if (v.type === 'video') {
        this.dialogType = 'video'
      }
      this.dialogImageUrl = v.url;
      this.dialogVisible = true;
    },
    //关闭放大弹窗
    handleClose() {
      this.dialogVisible = false
      this.$refs.video.pause();
    },
    creativeType(file) {
      let type = '';
      let url = file.url;
      if(url != null) {
        url = url.split('?')[0];
      }
      let name = file.name;
      if(name != null) {
        name = name.split('?')[0];
      }

      let urlTail = ((url != null && url.indexOf('.') >= 0) ? (url.substring(url.lastIndexOf('.') + 1)) : '').toLowerCase();
      let nameTail = ((name != null && name.indexOf('.') >= 0) ? (name.substring(name.lastIndexOf('.') + 1)) : '').toLowerCase();

      let imgList = ['jpg', 'jpeg', 'png', 'gif', 'bmp']
      let videoList = ['mp4', 'mov', 'avi', 'mp3', 'ogg', 'rmvb', 'mkv']
      if (imgList.includes(urlTail) || imgList.includes(nameTail)) {
        type = 'image'
      } else if (videoList.includes(urlTail) || videoList.includes(nameTail)) {
        type = 'video'
      }
      return type
    },
  }
}
</script>
<style lang="scss">
// 隐藏上传按钮
.hide .el-upload--picture-card {
  display: none;
}

// 添加/删除文件时去掉动画过渡
.el-upload-list__item {
  transition: none !important;
}

.el-upload-list--picture-card {
  display: block;
}

.upload-error {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center
}
</style>
